package com.cuz.daileetcode.utils;

import java.util.LinkedList;
import java.util.Objects;

public class ListNodeUtils {
    public static void main(String[] args) {
        ListNode listNode = listGenerate(1, 2, 3);
        printList(listNode);
    }

    public static ListNode listGenerate(int... val) {
        ListNode head = new ListNode(val[0]);
        ListNode temp = head;
        for (int index = 1; index < val.length; index++) {
            temp.next = new ListNode(val[index]);
            temp = temp.next;
        }
        return head;
    }

    public static void printList(ListNode node) {
        LinkedList<String> nodeValueList = new LinkedList<>();
        while (node != null) {
            nodeValueList.add(String.valueOf(node.val));
            node = node.next;
        }
        System.out.println(String.join("->", nodeValueList));
    }


    public static int distanceBetween(ListNode head, ListNode target) {
        Objects.requireNonNull(head);
        Objects.requireNonNull(target);
        int len = 0;
        while (head != target) {
            len++;
            head = head.next;
        }
        return len;
    }

    public static TailAndLen getTailAndLen(ListNode head) {
        Objects.requireNonNull(head);
        int len = 1;
        while (head.next != null) {
            head = head.next;
            len++;
        }
        return new TailAndLen(head, len);
    }

    public static int getLenNoLoop(ListNode head) {
        Objects.requireNonNull(head);
        int len = 1;
        while (head.next != null) {
            head = head.next;
            len++;
        }
        return len;
    }

    public static class TailAndLen {
        private ListNode tail;
        private int len;

        public ListNode getTail() {
            return tail;
        }

        public int getLen() {
            return len;
        }

        public TailAndLen(ListNode tail, int len) {
            this.tail = tail;
            this.len = len;
        }
    }
}
